package ClassicalCryptography;

public class VigenereCipher {
    public String encrypt(String plaintext, String key) {
        int lenPT = plaintext.length();
        int lenKey = key.length();
        StringBuilder res = new StringBuilder(lenPT);
        for (int i = 0; i < lenPT; i++) {
            res.append((char) (((int) (plaintext.charAt(i) - 'a') + (int) (key.charAt(i % lenKey)) - 'a') % 26 + 'a'));
        }
        return res.substring(0);
    }

    public String decrypt(String ciphertext, String key) {
        int lenCT = ciphertext.length();
        int lenKey = key.length();
        StringBuilder res = new StringBuilder(lenCT);
        for (int i = 0; i < lenCT; i++) {
            int temp = ((int) (ciphertext.charAt(i) - 'a') - (int) ((key.charAt(i % lenKey)) - 'a')) % 26;
            while (temp < 0) {
                temp += 26;
            }
            res.append((char) (temp + 'a'));
        }
        return res.substring(0);
    }
}
